package com.wmsafe.order.excelService;

import com.wmsafe.order.service.IOrderService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Service
public class ExcelExportService {

    @Autowired
    private IOrderService orderService;

    public void exportExcel(Class<?> entityClass, HttpServletResponse response) throws IOException {
        List<?> dataList = orderService.list();

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("数据列表");

        // 创建日期格式
        CreationHelper creationHelper = workbook.getCreationHelper();
        short dateFormat = creationHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss");

        // 设置日期格式
        CellStyle dateCellStyle = workbook.createCellStyle();
        dateCellStyle.setDataFormat(dateFormat);

        if (!dataList.isEmpty()) {
            Field[] fields = entityClass.getDeclaredFields();

            // 创建第一行，并写入字段名称
            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                String fieldName = field.getName();
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(fieldName);
            }

            // 写入数据
            for (int i = 0; i < dataList.size(); i++) {
                Object data = dataList.get(i);
                Row dataRow = sheet.createRow(i + 1);
                for (int j = 0; j < fields.length; j++) {
                    Field field = fields[j];
                    try {
                        field.setAccessible(true);
                        Object value = field.get(data);
                        String fieldValue = value != null ? value.toString() : "";
                        Cell cell = dataRow.createCell(j);

                        if (value instanceof LocalDateTime) {
                            LocalDateTime dateValue = (LocalDateTime) value;
                            cell.setCellValue(dateValue);
                            cell.setCellStyle(dateCellStyle); // 应用日期格式
                        } else if (value instanceof Date) {
                            Date dateValue = (Date) value;
                            cell.setCellValue(dateValue);
                            cell.setCellStyle(dateCellStyle); // 应用日期格式
                        }else {
                            setCellValue(cell, value);
                        }

//                        cell.setCellValue(fieldValue);

                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }

            for (int i = 0; i < fields.length; i++) {
                sheet.autoSizeColumn(i);
            }
        }

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=user_report.xlsx");

        // 将 workbook 写入文件
        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);

        workbook.close();
        outputStream.close();
    }

    private void setCellValue(Cell cell, Object value) {
        try{
            if (value instanceof String) {
                cell.setCellValue((String) value);
            } else if (value instanceof Integer) {
                cell.setCellValue((Integer) value);
            } else if (value instanceof Long) {
                cell.setCellValue((Long) value);
            } else if (value instanceof Double) {
                cell.setCellValue((Double) value);
            } else if (value instanceof Boolean) {
                cell.setCellValue((Boolean) value);
            } else {
                // handle other data types as needed
                String fieldValue = value != null ? value.toString() : "";
                cell.setCellValue(fieldValue);
            }
        }catch (Exception e){
            String fieldValue = value != null ? value.toString() : "";
            cell.setCellValue(fieldValue);
        }
    }
}
